package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.pojo.User;
import cn.edu.pzhu.javaweb.pojo.Userinfo;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.service.imp.UserServiceImp;
import cn.edu.pzhu.javaweb.util.Conver2MD5;

/**
 * Servlet implementation class RegistServlet
 */
@WebServlet("/regist")
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserServiceImp();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 先设置编码，避免中文乱码（之前遗漏）
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 2. 获取表单数据（不变）
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        String[] types = request.getParameterValues("type"); // 接收关注类型
        String captcha = request.getParameter("captcha");

        // 3. 合法性校验（不变）
        if(username==null || username.isEmpty() || password ==null || password.isEmpty()) {
            response.getWriter().print("<script>alert('信息不完整!');location.href='regist.jsp';</script>");	
            return;
        }

        // 4. 处理性别（不变）
        if(sex==null || sex.equals("")) {
            sex = "1";
        }

        // 【关键修复】处理关注类型：若未勾选（或默认勾选未传递），避免types为null
        if (types == null) {
            types = new String[0]; 
        }
        // 5. 创建用户信息对象
        String sec_password = Conver2MD5.getSHA256(Conver2MD5.getSHA256(username+password)+"pzhu");
        User user = new User(username, sec_password, 1);
        Userinfo userinfo = new Userinfo(username, email, Integer.valueOf(sex), JSON.toJSONString(types));
        Object code = request.getSession().getAttribute("SESSION_CAPTCHA");
        if(code==null){
            response.getWriter().print("<script>alert('验证码未初始化');location.href='regist.jsp';</script>");
            return;
        }
        String session_captcha = (String)code;
        if(session_captcha.equalsIgnoreCase(captcha)) {
            Result<String> result =userService.regist(user, userinfo);
            if(result.getCode()==0) {
                response.getWriter().print("<script>alert('注册成功');location.href='login.jsp';</script>");
            }else {
                response.getWriter().print("<script>alert('"+result.getMessage()+"');location.href='regist.jsp';</script>");

            }
        }else {
            response.getWriter().print("<script>alert('验证码错误，注册失败');location.href='regist.jsp';</script>");
        }
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
